<script lang="ts">
import type { BigNumber } from '@peng_kai/kit/libs/bignumber';
import type { EChartsOption } from '@peng_kai/kit/libs/echarts';
import { useDraggable } from '@peng_kai/kit/libs/vueuse';
import { ECharts as EChartsRenderer } from '@peng_kai/kit/vue/components';
import { CloseBtn } from '~comp/card';
import { emitGamePM, useOnGamePM } from './helpers';

interface TLog {
  currency: string;
  betAmount: BigNumber.Instance;
  profitAmount: BigNumber.Instance;
}

function getEchartsConfig(data: number[] = []): EChartsOption {
  return {
    grid: {
      left: '0%',
      right: '0%',
      bottom: '0%',
      top: '0%',
      containLabel: false,
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#3E404C',
      borderColor: '#3E404C',
      confine: true,
      textStyle: {
        color: '#fff', // 自定义文字颜色
      },
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLine: { // 去掉 X 轴的线
        lineStyle: {
          color: 'transparent', // 或者你可以设置为透明色 'transparent'
        },
      },
      axisLabel: { show: false },
    },
    yAxis: {
      type: 'value',
      splitLine: { show: false },
      axisLine: { show: false },
      axisLabel: { show: false },
    },
    series: [
      {
        name: 'Profit',
        type: 'line',
        symbol: 'none',
        smooth: 0.4,
        areaStyle: { opacity: 0.3 },
        lineStyle: { width: 2 },
        data: [0, ...data],
      },
    ],
    visualMap: [
      {
        show: false,
        dimension: 1,
        pieces: [
          { color: '#4ade80', gte: 0.000000001 }, // 只能这样，这是个echarts bug
          { color: '#ef4444', lt: 0 },
        ],
      },
    ],
  };
}
</script>

<script lang="ts" setup>
const currencySotre = useCurrencyStore();
const logList = ref<TLog[]>([]);
const profitLogList = ref<number[]>([]);
const totalWagered = computed(() => logList.value.map(x => x.betAmount).reduce((p, c) => p.plus(c), bignumber(0)));
const totalProfit = computed(() => logList.value.map(x => x.profitAmount).reduce((p, c) => p.plus(c), bignumber(0)));
const winCount = computed(() => logList.value.filter(x => x.profitAmount.gte(0)).length);
const loseCount = computed(() => logList.value.filter(x => x.profitAmount.lt(0)).length);
const $target = ref<HTMLElement | null>(null);
const $handle = ref<HTMLElement | null>(null);
const { style } = useDraggable($target, {
  initialValue: { x: 40, y: 40 },
  containerElement: document.body,
  handle: $handle,
});
const enabled = ref(false);
const lastCurrency = ref(currencySotre.cryptoName);
const echartsConfig = computed(() => {
  return getEchartsConfig(profitLogList.value);
});
function addLog(log: TLog) {
  if (!enabled.value)
    return;

  if (lastCurrency.value && lastCurrency.value !== log.currency) {
    cleanLog();
  }

  lastCurrency.value = log.currency;
  logList.value.push(log);
  profitLogList.value.push(totalProfit.value.plus(log.profitAmount).toNumber());
}

function cleanLog() {
  logList.value = [];
  profitLogList.value = [];
}

function close() {
  enabled.value = false;
  emitGamePM.changeLiveChartEnabled({ enabled: false });
}

watch(enabled, cleanLog);

useOnGamePM('addMyLog', (data) => {
  addLog({
    currency: data.currency,
    betAmount: bignumber(data.betAmount),
    profitAmount: bignumber(data.profitAmount),
  });
});
useOnGamePM('changeLiveChartEnabled', (data) => {
  enabled.value = data.enabled;
});
</script>

<template>
  <div
    v-show="enabled" ref="$target" :style="style"
    class="fixed z-100 grid w-75 gap-2 rounded-1.5 bg-sys-layer-d p-3 shadow-[0_0_10px_#0004]"
  >
    <!-- 头部 -->
    <div ref="$handle" class="relative h-10 flex cursor-grab items-center text-lg active:cursor-grabbing">
      <div
        class="mr-2 size-6 flex-center rounded-full bg-brand transition-all hover:rotate-90 active:scale-90"
        @click="cleanLog()"
      >
        <i class="i-ri:refresh-line cursor-pointer text-base lh-none" />
      </div>
      <div class="flex-center select-none self-stretch font-600">
        {{ $t('6QPmZtYlTwBWuChp7pgCr') }}
      </div>

      <CloseBtn class="ml-auto" @click="close()" />
    </div>

    <!-- 统计面板 -->
    <div class="grid grid-cols-[2fr_1fr] items-center gap-2 rounded-2 bg-sys-layer-c p3 text-sm">
      <div>
        <div class="mb-1 text-sys-text-body">
          {{ $t('iygk8Ly05wCeUYc1LrlRp') }}
        </div>
        <TAmount :value="totalProfit" :symbol="lastCurrency" iconPos="left" :decimals="8" format="pad-dec" colored="full" />
      </div>
      <div>
        <div class="mb-1 text-sys-text-body">
          {{ $t('kKo58Saue7qlcydaT9inm') }}
        </div>
        <div class="text-green">
          {{ winCount }}
        </div>
      </div>
      <div>
        <div class="mb-1 text-sys-text-body">
          {{ $t('dhrtoi6QVwH9fGv2O4Cnb') }}
        </div>
        <TAmount :value="totalWagered" :symbol="lastCurrency" iconPos="left" :decimals="8" format="pad-dec" />
      </div>
      <div>
        <div class="mb-1 text-sys-text-body">
          {{ $t('drOSmJTEl6MfCwyjeYgs') }}
        </div>
        <div>
          {{ loseCount }}
        </div>
      </div>
    </div>

    <!-- 图表 -->
    <div class="h-50 rounded-2 bg-sys-layer-c p3">
      <EChartsRenderer
        v-if="profitLogList.length"
        class="!h-full !w-full" theme="light"
        updateMode="data" :echartOption="echartsConfig"
      />
      <div v-else class="h-full flex-center text-sm text-sys-text-body">
        {{ $t('zvEHnJPsFo7Xqkn08apQ') }}
      </div>
    </div>
  </div>
</template>
